﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Facebook;

namespace SocialPack.Helpers
{
    public static class FacebookUtil
    {
        private static readonly log4net.ILog _log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public static bool DoILikeIt(string token, string category, int minNumberOfLikes)
        {
            var client = new FacebookClient(token);
            var likes = (IDictionary<string, object>)client.Get("me/likes");

            bool likesCategory = false;

            foreach (KeyValuePair<string, object> data in likes)
            {
                JsonArray allLikes = (JsonArray)data.Value;

                int count = (from likeItem in allLikes
                             where (likeItem as JsonObject)["name"].ToString().ToLower().Contains(category.ToLower())
                             select likeItem).Count();


                likesCategory = count >= minNumberOfLikes;
            }

            return likesCategory;
        }


        /// <summary>
        /// The method to Decode your Base64 strings.
        /// </summary>
        /// <param name="encodedData">The String containing the characters to decode.</param>
        /// <returns>A String containing the results of decoding the specified sequence of bytes.</returns>
        private static string DecodeFrom64(string encodedData)
        {
            int padChars = (encodedData.Length % 4) == 0 ? 0 : (4 - (encodedData.Length % 4));

            StringBuilder result = new StringBuilder(encodedData, encodedData.Length + padChars);
            result.Append(String.Empty.PadRight(padChars, '='));

            result.Replace('-', '+');
            result.Replace('_', '/');

            byte[] encodedDataAsBytes = System.Convert.FromBase64String(result.ToString());
            string returnValue = System.Text.Encoding.UTF8.GetString(encodedDataAsBytes);

            return returnValue;
        }
    }
}